package com.example.dayu521.sg_oss.conf;

import com.example.dayu521.sg_oss.conf.prop.MyMinioProperties;
import io.minio.MinioClient;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@EnableConfigurationProperties({MyMinioProperties.class})
public class MinioCnf {
    @Profile("prototype")
    @Bean
    public MinioClient minioClientPrototype(MyMinioProperties myMinioProperties) {
        var httpc = new OkHttpClient().newBuilder()
                .addInterceptor(p -> {
                    //替换真正的请求地址
                    var s = p.request().newBuilder();
                    var url = p.request().url();
                    var rurl = url.newBuilder().build().resolve(myMinioProperties.getEndpoint());
                    s.url(url.newBuilder().host(rurl.host()).port(rurl.port()).build());
                    var req = s.build();
                    return p.proceed(req);
                })
                .build();
        var minioClient =
                MinioClient.builder()
                        //为了签名一致
                        //因为当前服务部署在docker中,而本地启动当前服务,他们俩访问minio服务时,计算的签名不一样
                        //所以,为了签名一致,就先用一个假的主机名进行签名,然后再拦截器中恢复外部访问的
                        .endpoint(myMinioProperties.getSignature_host())
                        .credentials(myMinioProperties.getAcesskey(), myMinioProperties.getSecretkey())
                        .httpClient(httpc)
                        .build();
        return minioClient;
    }

    @Profile("dev")
    @Bean
    public MinioClient minioClient(MyMinioProperties myMinioProperties) {
        var minioClient =
                MinioClient.builder()
                        .endpoint(myMinioProperties.getEndpoint())
                        .credentials(myMinioProperties.getAcesskey(), myMinioProperties.getSecretkey())
                        .build();
        return minioClient;
    }
}
